<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="never" class="group-tree-card">
          <template #header>
            <div class="card-header">
              <span>设备组</span>
              <el-button type="primary" size="small" @click="handleAddRoot">新建组</el-button>
            </div>
          </template>
          <div class="group-tree-container">
            <el-tree
              ref="groupTreeRef"
              :data="groupTree"
              node-key="id"
              default-expand-all
              highlight-current
              :props="defaultProps"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <div class="action-buttons">
                    <!-- 添加事件阻止修饰符 -->
                    <el-button type="primary" link size="small" @click.stop="handleAddChild(data)">
                      <el-icon><Plus /></el-icon>
                    </el-button>
                    <el-button type="success" link size="small" @click.stop="handleEdit(data)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button type="danger" link size="small" @click.stop="handleDelete(data)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </el-card>
      </el-col>

      <el-col :span="18">
        <el-card shadow="never" class="group-detail-card">
          <template #header>
            <div class="card-header">
              <span>{{ currentGroup.id ? `组详情: ${currentGroup.name}` : '组详情' }}</span>
              <el-button @click="backToDevice">返回设备管理</el-button>
            </div>
          </template>
          <div v-if="!currentGroup.id" class="empty-tip">
            请选择一个设备组查看详情
          </div>
          <div v-else class="group-detail">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="组名称">{{ currentGroup.name }}</el-descriptions-item>
              <el-descriptions-item label="上级组">{{ currentGroup.parent ? currentGroup.parent.name : '无' }}</el-descriptions-item>
              <el-descriptions-item label="组路径">{{ currentGroup.full_path_name }}</el-descriptions-item>
              <el-descriptions-item label="层级">{{ currentGroup.level }}</el-descriptions-item>
              <el-descriptions-item label="描述" :span="2">{{ currentGroup.description || '无' }}</el-descriptions-item>
            </el-descriptions>

            <div class="device-list">
              <h3>组内设备</h3>
              <el-table v-loading="deviceLoading" :data="deviceList" border stripe style="width: 100%">
                <el-table-column type="index" width="50" label="#" align="center" />
                <el-table-column prop="name" label="设备名称" min-width="150" />
                <el-table-column prop="serial_no" label="序列号" min-width="150" />
                <el-table-column prop="protocol" label="协议类型" min-width="100" />
                <el-table-column prop="location" label="位置" min-width="150" />
                <el-table-column label="状态" width="80" align="center">
                  <template #default="scope">
                    <el-tag :type="statusType(scope.row.status)">{{ statusText(scope.row.status) }}</el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 设备组表单对话框 -->
    <el-dialog
      :title="formTitle"
      v-model="dialogFormVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form ref="groupFormRef" :model="groupForm" :rules="rules" label-width="100px">
        <el-form-item label="组名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入组名称" />
        </el-form-item>
        <el-form-item label="上级组" prop="parent_id" v-if="!groupForm.is_root">
          <el-tree-select
            v-model="groupForm.parent_id"
            :data="groupTree"
            placeholder="请选择上级组"
            check-strictly
            :props="defaultProps"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="groupForm.description"
            type="textarea"
            placeholder="请输入描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getDeviceGroupTree, getDeviceGroupDetail, addDeviceGroup, editDeviceGroup, deleteDeviceGroup } from '@/api/device'
import { getDeviceList } from '@/api/device'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'

const router = useRouter()

// 设备组树数据
const groupTree = ref([])
const groupTreeRef = ref(null)
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 当前选中的设备组
const currentGroup = ref({})

// 设备列表数据
const deviceList = ref([])
const deviceLoading = ref(false)

// 获取设备组树
const getGroupTree = async () => {
  try {
    const res = await getDeviceGroupTree()
    groupTree.value = res.data || []
  } catch (error) {
    console.error('获取设备组树失败', error)
  }
}

// 获取设备组详情
const getGroupDetail = async (id) => {
  try {
    const res = await getDeviceGroupDetail(id)
    currentGroup.value = res.data
    // 获取该组下的设备
    getGroupDevices(id)
  } catch (error) {
    console.error('获取设备组详情失败', error)
    currentGroup.value = {}
  }
}

// 获取设备组下的设备
const getGroupDevices = async (groupId) => {
  deviceLoading.value = true
  try {
    const res = await getDeviceList({ group_id: groupId })
    deviceList.value = res.data.data || []
  } catch (error) {
    console.error('获取设备列表失败', error)
    deviceList.value = []
  } finally {
    deviceLoading.value = false
  }
}

// 设备状态处理
const statusText = (status) => {
  const statusMap = {
    0: '离线',
    1: '在线',
    2: '故障'
  }
  return statusMap[status] || '未知'
}

const statusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || ''
}

// 树节点点击
const handleNodeClick = (data) => {
  try {
    if (!data?.id) {
      console.error('Invalid node data:', data)
      return
    }
    getGroupDetail(data.id)
  } catch (error) {
    console.error('Node click handler error:', error)
  }
}

// 表单相关
const dialogFormVisible = ref(false)
const groupFormRef = ref(null)
const formType = ref('add') // add 或 edit
const formTitle = computed(() => {
  if (formType.value === 'add') {
    return groupForm.is_root ? '新建根设备组' : '新建子设备组'
  } else {
    return '编辑设备组'
  }
})

// 设备组表单数据
const groupForm = reactive({
  id: undefined,
  name: '',
  parent_id: undefined,
  description: '',
  is_root: false
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入组名称', trigger: 'blur' }],
  parent_id: [{ required: true, message: '请选择上级组', trigger: 'change' }]
}

// 重置表单
const resetForm = () => {
  if (groupFormRef.value) {
    groupFormRef.value.resetFields()
  }
  Object.assign(groupForm, {
    id: undefined,
    name: '',
    parent_id: undefined,
    description: '',
    is_root: false
  })
}

// 添加根设备组
const handleAddRoot = () => {
  resetForm()
  formType.value = 'add'
  groupForm.is_root = true
  dialogFormVisible.value = true
}

// 添加子设备组
const handleAddChild = (data) => {
  resetForm()
  formType.value = 'add'
  groupForm.is_root = false
  groupForm.parent_id = data.id
  dialogFormVisible.value = true
}

// 编辑设备组
const handleEdit = (data) => {
  resetForm()
  formType.value = 'edit'
  Object.assign(groupForm, {
    id: data.id,
    name: data.name,
    parent_id: data.parent_id,
    description: data.description,
    is_root: data.parent_id === 0
  })
  dialogFormVisible.value = true
}

// 删除设备组
const handleDelete = (data) => {
  ElMessageBox.confirm(`是否确认删除设备组：${data.name}？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDeviceGroup(data.id)
      ElMessage.success('删除成功')
      getGroupTree()
      if (currentGroup.value.id === data.id) {
        currentGroup.value = {}
      }
    } catch (error) {
      console.error('删除设备组失败', error)
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  // 处理根设备组逻辑
  if (groupForm.is_root) {
    groupForm.parent_id = 0
  }
  
  groupFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (formType.value === 'add') {
          await addDeviceGroup(groupForm)
          ElMessage.success('添加成功')
        } else {
          await editDeviceGroup(groupForm)
          ElMessage.success('更新成功')
        }
        dialogFormVisible.value = false
        getGroupTree()
        // 如果编辑的是当前选中的设备组，刷新详情
        if (formType.value === 'edit' && currentGroup.value.id === groupForm.id) {
          getGroupDetail(groupForm.id)
        }
      } catch (error) {
        console.error('保存设备组失败', error)
      }
    }
  })
}

// 返回设备管理
const backToDevice = () => {
  router.push({ path: '/device' })
}

onMounted(() => {
  getGroupTree()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-card__header) {
  padding: 10px 20px;
}

.group-tree-card {
  height: 100%;
}

.group-tree-container {
  overflow: auto;
  max-height: calc(100vh - 200px);
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}

.action-buttons {
  opacity: 0;
  transition: opacity 0.2s;
}

.custom-tree-node:hover .action-buttons {
  opacity: 1;
}

.group-detail-card {
  height: 100%;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 40px 0;
  font-size: 16px;
}

.group-detail {
  .device-list {
    margin-top: 20px;
    
    h3 {
      margin-bottom: 15px;
      font-weight: normal;
      color: #606266;
    }
  }
}
</style> 